package models

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"smart_home/mqtt/conf"
	"time"
	"tools"
	"xfyun"
)

type User struct {
	Id            string `json:"id"`
	Mobile        int64  `json:"mobile"`
	CreateTime    int64  `json:"create_time"`
	LastLoginTime int64  `json:"last_login_time"`
	LastLoginIp   int64  `json:"last_login_ip"`
	Status        int64  `json:"status"`
	NickName      string `json:"nick_name"`
	Birthday      string `json:"birthday"`
	Sex           int64  `json:"sex"`
	Avatar        string `json:"avatar"`
}

type userResult struct {
	HttpResult
	Result *User
}

func GetUserById(uid string) (*User, error) {
	s := time.Now().Format("2006年1月2日")
	r, err := httplib.Get(fmt.Sprintf("%s/v2/mqtt/user", conf.ApiHost)).
		Header("token", tools.MD5Encode(s)).
		Param("username", "app").
		Param("client_id", uid).
		Bytes()

	if err != nil {
		return nil, err
	}

	res := userResult{}
	err = json.Unmarshal(r, &res)
	if err != nil {
		return nil, err
	}

	if res.Code == 0 {
		return nil, errors.New(res.Msg)
	}

	return res.Result, nil
}

func GetUserBySta(sta string) (*User, error) {
	s := time.Now().Format("2006年1月2日")
	r, err := httplib.Get(fmt.Sprintf("%s/v2/mqtt/user", conf.ApiHost)).
		Header("token", xfyun.MD5Encode(s)).
		Param("username", "equipment").
		Param("client_id", sta).
		Bytes()

	if err != nil {
		return nil, err
	}

	res := userResult{}
	err = json.Unmarshal(r, &res)
	if err != nil {
		return nil, err
	}

	if res.Code == 0 {
		return nil, errors.New(res.Msg)
	}

	return res.Result, nil
}
